package com.example.lx6_4.order

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.base.db.OrderDao
import com.example.base.entity.OrderEntity
import com.example.base.entity.OrderEntityItem
import com.example.base.mvvm.BaseViewModel
import com.example.base.net.ApiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject

@HiltViewModel
class OrderViewModel @Inject constructor(val apiService: ApiService,val orderDao: OrderDao) : BaseViewModel() {

    fun getOrder(s:String) : Flow<PagingData<OrderEntityItem>>{
//        return Pager(config = PagingConfig(pageSize = 10), pagingSourceFactory = {
//            OrderSource(apiService)
//        }).flow.cachedIn(viewModelScope)
        return httpFlow { OrderSource(apiService,orderDao,s) }
    }

    val addOrderData = MutableLiveData<OrderEntityItem>()

    fun getAddOrder(body: Any){
        httpRequest({apiService.getAddOrder(toBody(body))},addOrderData::postValue)
    }

    val addOrderRoom = MutableLiveData<Long>()

    fun getAddOrderRoom(body: OrderEntityItem){
        httpRoom({orderDao.getInsertOrder(body)},addOrderRoom::postValue)
    }

    val deleteOrderData = MutableLiveData<Boolean>()

    fun getDeleteOrder(id:Int){
        httpRequest({apiService.getDelete(id)},deleteOrderData::postValue)
    }

    val deleteOrderRoom = MutableLiveData<Int>()

    fun getDeleteOrderRoom(body: OrderEntityItem){
        httpRoom({orderDao.getDeleteOrder(body)},deleteOrderRoom::postValue)
    }

}